import Api from '../service/Api';
import {emojiString, chatTimeFormat, receiveTextFmt} from '../common/Function'
import ChatManager from './ChatManager';
import ChoicePage from '../pages/news_mass_choice';
import JsBridge from '../service/JsBridge';
import {fileExt} from '../common/Function';
import Session from '../service/Session';

class Message {
  constructor() {
    this.data = null;
    this.jqArr = null;
    this.lastTime = null;
    this._renderBox = this._renderBox.bind(this);
    this._bindEvent = this._bindEvent.bind(this);
    this.dataTransfrom = this.dataTransfrom.bind(this);
    this.clearLastTime = this.clearLastTime.bind(this);
  }

  _bindEvent(ele, message) {
    const type = message.MsgType;
    switch (type) {
      case '2':
        ele.click(function() {
          console.log(`---------message-2`)
          console.log(message)
          if (message.LocalPath) { // 如果已下载
            // 调取文件打开接口
            JsBridge.sendRequest("message.open", {path: message.LocalPath})
          } else { // 没有下载
            // 调取文件下载接口
            JsBridge.sendRequest("message.file", message).then(resp => {
              // 下载完成
              console.log(`----------------resp.file`)
              console.log(resp)
              if (!resp.success) {
                ele.find('.finish').css('display','none');
                ele.find('.progress').css('display','block');
                ele.find('.progress').find('p').text('下载失败');
                ele.find('.progress').find('span').text('重试');
              } else {
                ele.find('.finish').css('display','none');
                ele.find('.progress').css('display','block');
                ele.find('.progress').find('p').text('下载完成');
                ele.find('.progress').find('span').text('打开');
                // 更新messges的状态
                message.LocalPath = resp.path;
//               JsBridge.sendRequest("message.open", {path: message.LocalPath})//文件打开
                ChatManager.processMessages([message], false);
              }

            });
          }

        });

        ele.bind("contextmenu", function(){ // 禁止默认右键
				    return false;
				});
       	ele.mousedown(function(e) {      // 文件右键事件
			    console.log('ssssssssssssssssssssssss');
			    if (3 == e.which) {     // 右键为3
              const _this = $(this);
              const tpl = $(`
                <div class='right_key'>
                  <p class='zf'><img src='img/news_public/forward.png'/>转发</p>
                  <p class='bc'><img src='img/news_public/save_the_local.png'/>保存到本地</p>
                  <p class='dk'><img src='img/news_public/save_the_local.png'/>打开文件位置</p>
                </div>`)
              tpl.on('click', '.zf', function(e) {
                e.stopPropagation();
                // alert('-----------------------转发')
                tpl.remove();
                window._needzf = {path: message.LocalPath, type: 2, backId: message.Receive_ID}; // 将要转发的文件路径放入全局
                ChoicePage.render();
               // $(this).prev().css('display','none');
              })
              tpl.on('click', '.bc', function(e) {
                e.stopPropagation();
//              alert('-----------------------保存')
//               alert(message.LocalPath);
                JsBridge.sendRequest("file.save", {path: message.LocalPath});
                tpl.remove();
              })
              tpl.on('click', '.dk', function(e) {
                e.stopPropagation();
//              alert('-----------------------打开')
//                alert(message.LocalPath);

                JsBridge.sendRequest("file.open", {path: message.LocalPath});
                tpl.remove();
              })
			        _this.append(tpl);
              _this.attr('disabled',"true");


			    }
			     // 点击非emoji选择面板隐藏事件
      $(".right").unbind('click');
      $(".right").on('click', function(e) {
        // 遍历点击传递路径，找是否有emoji_div
        try {
          e.path.forEach(item => {
            if (item.className == 'right_key') {
              throw new Error(`find right_key`)
            }
          })
        } catch (e) {
          $(".right_key").css("display", "none");

        }
        return true;
      })

        })
        break;
      case '3':
      	ele.bind("contextmenu", function(){ // 禁止默认右键
				    return false;
				});
        ele.click(function(e) {
        	console.log(e)
          	JsBridge.sendRequest("message.image", message);
        });
       	ele.mousedown(function(e) {
			    console.log('ssssssssssssssssssssssss');

          if (3 == e.which) {     // 右键为3
              const _this = $(this);
              const tpl = $(`
                <div class='right_key'>
                  <p class='zf'><img src='img/news_public/forward.png'/>转发</p>
                  <p class='bc'><img src='img/news_public/save_the_local.png'/>保存到本地</p>
                  <p class='dk'><img src='img/news_public/save_the_local.png'/>打开文件位置</p>
                </div>`)
              tpl.on('click', '.zf', function(e) {
                e.stopPropagation();
                // alert('-----------------------转发')
                tpl.remove();
                window._needzf = {path: message.LocalPath, type: 3, backId: message.Receive_ID}; // 将要转发的文件路径放入全局
                // alert(message.LocalPath); // 将要转发的文件路径放入全局
                ChoicePage.render();
               // $(this).prev().css('display','none');
              })
              tpl.on('click', '.bc', function(e) {
                e.stopPropagation();

                // alert('-----------------------保存')
                // alert(message.LocalPath);
                JsBridge.sendRequest("file.save", {path: message.LocalPath});
                tpl.remove();
              })
              tpl.on('click', '.dk', function(e) {
                e.stopPropagation();
                // alert('-----------------------打开')
                // alert(message.LocalPath);

                JsBridge.sendRequest("file.open", {path: message.LocalPath});
                tpl.remove();
              })
			        _this.append(tpl);
              _this.attr('disabled',"true");

			    };
          			     // 点击非emoji选择面板隐藏事件
      $(".right").unbind('click');
      $(".right").on('click', function(e) {
        // 遍历点击传递路径，找是否有emoji_div
        try {
          e.path.forEach(item => {
            if (item.className == 'right_key') {
              throw new Error(`find right_key`)
            }
          })
        } catch (e) {
          $(".right_key").css("display", "none");

        }
        return true;
      })
			  })

        break;
      case '4':               //点击音频
    	console.log('------------------------点击音频')
        ele.children('a').val(1);
        ele.click(function() {
//					return alert(message.Message_ID)
        	if(ele.children('a').val()==0){return ;}
        	else{
			        	ele.children('a').val(0);
			        	ele.find('.dian').css("display","none");
			        	//将其置为已读
			        	const userInfo = Session.getUser();
			        	const {User_ID, SessionID, Unit_ID} = userInfo;
								Api.post('/BasePlate/Interface/IInterfaceJson.asmx/Message_ReadMulti', {
					        User_ID,
					        SessionID,
					        Unit_ID,
					        IsRead: 2,
					        MessageIDs: message.Message_ID
					      }).then(resp => {

					          JsBridge.sendRequest("message.read", {ids: [message.Message_ID], status: 2});
					          ChatManager.pollMessage();
					        // }
					      })
			          ele.children('a').addClass('voice-animation');
			          JsBridge.sendRequest("message.audio", message).then(resp=>{
			          ele.children('a').removeClass('voice-animation');
			      				setTimeout(function(){       //延时执行函数
											ele.children('a').val(1);
										},2000)
									clearTimeout();
			//          alert(`播放完毕`);
			          });
        	}console.log(message)
        })
        break;
      case '5':
        ele.click(function() {
          JsBridge.sendRequest("message.video", message);
        })
        break;
      default:
        ;
    }
  }


  _renderMsgType(message) {
  	var f_size=message.MsgUrl.split('|')[2];
  	var flie_size=0;
  	if(f_size>1073741824){f_size=f_size/1073741824;flie_size='G';}else if(f_size>1048576){f_size=f_size/1048576;flie_size='MB';}else if(f_size>1024){f_size=f_size/1024;flie_size='KB';}else{flie_size='B';};

			f_size=parseInt(f_size*100)/100;
  	flie_size=f_size+flie_size;
    switch (message.MsgType) {
      case '2':{     //文本文件
        var $na=fileExt(message.MsgUrl.split('|')[1]);
        const userInfo = Session.getUser();
        console.log(message)
        console.log('---------------------111111111')
        if(message.Send_ID==userInfo.User_ID){
	        return `
	          <div class="file file2 ${$na}"><p title="${message.MsgUrl.split('|')[1]}">${message.MsgUrl.split('|')[1]} (<span>${flie_size}</span>)</p><div class="finish"><p>发送完成</p><span>打开</span></div>
	          <div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 10%;"></div><p>发送中...<span class="sr-only">(0%)</span></p><span>取消</span><span>暂停</span></div></div>
	        `;}else if(!message.LocalPath){
				        	return `
				          <div class="file file2 ${$na}"><p title="${message.MsgUrl.split('|')[1]}">${message.MsgUrl.split('|')[1]} (<span>${flie_size}</span>)</p><div class="finish"><p></p><span>下载</span></div>
				          <div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 10%;"></div><p>下载中...<span class="sr-only">(0%)</span></p><span>取消</span><span>暂停</span></div></div>
				        `;}else{
				        	return `
				          <div class="file file2 ${$na}"><p title="${message.MsgUrl.split('|')[1]}">${message.MsgUrl.split('|')[1]} (<span>${flie_size}</span>)</p><div class="finish"><p>下载完成</p><span>打开</span></div>
				          <div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 10%;"></div><p>下载中...<span class="sr-only">(0%)</span></p><span>取消</span><span>暂停</span></div></div>
				        `;
        	}
        };
      case '3':
        if (message.LocalPath && !message.MsgUrl.split('|')[0]) {
          return `
            <div class="img"><img class="my-img" src="../img/news_public/loading.gif" /></div>
          `
        } else {
          return `
            <div class="img"><img class="my-img" src="${API.baseUrl}Upload/${message.MsgUrl.split('|')[0]}" /></div>
          `;
        };
        setTimeout(function(){       //延时执行函数
           $('.main.discu').scrollTop($('.main.discu')[0].scrollHeight); //延时跳到最底部（图片加载后，高度变化）
        },2500)
         clearTimeout();
      ;
      case '4': // 音频
      var time_a=message.MsgUrl.split('|')[3];
      var t=time_a;
      var is_r=message.IsRead;
    	if(!t){t='';}
      if(time_a>60){time_a=60;}
//    if(is_r!=2){$('.dian').css('display','block');}else{$('.dian').css('display','none');}
      var length_a=time_a*2+50;
        return `
          <div class="voice">
            <a href="###" style="width:${length_a}px"><s class="laba"></s></a>
            ${is_r == 2 ? '' : '<img class="dian" src="img/news_public/dian.png" />'}
            <span><b>${t}</b>''</span></div>
        `;
      case '5':
      	 const userInfo = Session.getUser();
        if(message.Send_ID==userInfo.User_ID){
	        return `
	          <div class="file file5"><p title="${message.MsgUrl.split('|')[1]}">${message.MsgUrl.split('|')[1]} (<span>${flie_size}</span>)</p><div class="finish"><p>发送完成</p><span>打开</span></div>
	          <div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div><p>发送中...<span class="sr-only">(0%)</span></p><span>取消</span><span>暂停</span></div></div>
	        `;}else{
        	 return `
          <div class="file file5"><p title="${message.MsgUrl.split('|')[1]}">${message.MsgUrl.split('|')[1]} (<span>${flie_size}</span>)</p><div class="finish"><p></p><span>下载</span></div>
          <div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div><p>下载中...<span class="sr-only">(0%)</span></p><span>取消</span><span>暂停</span></div></div>
        `;
        };
      default:
        return `
          <div class="text">${receiveTextFmt(emojiString(message.MsgContent))}</div>
        `;
    }
  }

  _renderBox(message, userInfo, type) {
    let box;
    switch (type) {
      case 1:
      if(message.Receive_ID>0){
		      var names=0;
		      var is_name=0;

		      if(message.IsRead==2){names='已读';is_name='yidu';}
		      else if(message.IsRead==1){names='已送达';is_name='yisd';}
		      			else{names='未读';is_name='';};
		        box = $(`<li class="me" data-msgid="${message.Message_ID ? message.Message_ID : '-1'}" data-key="${message.ClientCode}-${message.ClientMessage_ID}">
		            <img src="${userInfo.HeadPic ? Api.imageUrl(userInfo.HeadPic) : 'img/news_public/user_6.png'}"/>
		            <div>
		                ${this._renderMsgType(message)}
		                <span class="prompt ${is_name}">${names}</span>
		            </div>
		        </li>`);
       }else{
       	box = $(`<li class="me" data-msgid="${message.Message_ID ? message.Message_ID : '-1'}" data-key="${message.ClientCode}-${message.ClientMessage_ID}">
            <img src="${userInfo.HeadPic ? Api.imageUrl(userInfo.HeadPic) : 'img/news_public/user_6.png'}"/>
            <div>
            		${this._renderMsgType(message)}
            </div>
        </li>`);

       }

        this._bindEvent(box.find("div div"), message)
        return box;
      case 2:
        box = $(`<li class="other" data-msgid="${message.Message_ID ? message.Message_ID : '-1'}" data-key="${message.ClientCode}-${message.ClientMessage_ID}">
            <img src="${userInfo.HeadPic ? Api.imageUrl(userInfo.HeadPic) : 'img/news_public/user_6.png'}"/>
            <div>
                ${(message.Receive_ID < 0 || message.Send_ID < 0) ? ('<span>'+ userInfo.UserName + '</span>') : '<span class="ss"></span>'}
                ${this._renderMsgType(message)}
            </div>
        </li>`);
        this._bindEvent(box.find("div div"), message)
        return box;
      case 3: // 系统盒子
        box = $(`<li class="other">
            <img src="img/news_public/user_1.png"/>
            <div>
                <span>系统消息</span>
                ${this._renderMsgType(message)}
            </div>
        </li>`);
        this._bindEvent(box.find("div div"), message)
        return box;
      default:
        box = $(`<li class="other" data-msgid="${message.Message_ID ? message.Message_ID : '-1'}" data-key="${message.ClientCode}-${message.ClientMessage_ID}>
            <img src="#"/>
            <div>
                <span>未命名</span>
                ${this._renderMsgType(message)}
            </div>
        </li>`);
        this._bindEvent(box.find("div div"), message)
        return box;
    }
  }

  dataTransfrom(m, getLastMsg) {
    this.data = $.extend({}, m);
    const userInfo = JSON.parse(localStorage.getItem('yxtUser'));
    const { messages } = this.data;

    if (getLastMsg) {
      let item = m.message;
      if (m.id == '0') { // Boxtype 3 -- 系统盒子
        this.jqArr = [{box: this._renderBox(item, userInfo, 3), time: item.SendDate}]
      }else if (item.Send_ID === userInfo.User_ID) {  // Boxtype 1 --本人消息
        this.jqArr = [{box: this._renderBox(item, userInfo, 1), time: item.SendDate}]
      } else if (item.sender.User_ID) {          // Boxtype 2 --其他人消息
        this.jqArr = [{box: this._renderBox(item, item.sender, 2), time: item.SendDate}]
      } else {                    // Boxtype default 未知人消息
        this.jqArr = [{box: this._renderBox(item, item.sender), time: item.SendDate}]
      }
    } else {
      if (messages.length > 0) {
        let arr = [];
        messages.forEach(item => {
            if (m.id == '0') { // Boxtype 3 -- 系统盒子
              arr.unshift({box: this._renderBox(item, userInfo, 3), time: item.SendDate})
            } else if (item.Send_ID === userInfo.User_ID) {  // Boxtype 1 --本人消息
              arr.unshift({box: this._renderBox(item, userInfo, 1), time: item.SendDate})
            } else if (item.sender.User_ID) {          // Boxtype 2 --其他人消息
              arr.unshift({box: this._renderBox(item, item.sender, 2), time: item.SendDate})
            } else {                    // Boxtype default 未知人消息
              arr.unshift({box: this._renderBox(item, item.sender), time: item.SendDate})
            }
        });
        this.jqArr = arr;
      } else {
        this.jqArr = [];
      }
    }

    return this;
  }

  appendTo(c) {
    if (this.jqArr.length < 1) {
      return this;
    }
    this.jqArr.forEach((item) => {
      const lastTime = moment(item.time, "YYYY/M/D HH:mm:ss");
      if(!this.lastTime || Math.abs(lastTime.diff(this.lastTime, 's')) > 300) { // 没有最后的时间或时间差大于10分钟 就渲染时间标签
        $(`<p>${chatTimeFormat(lastTime, moment())}</p>`).appendTo(c);
      }
      item.box.appendTo(c);
      this.lastTime = lastTime;
    })
    return this;
  }

  prependTo(c) {
    if (this.jqArr.length < 1) {
      return this;
    }
    this.jqArr.forEach((item, index) => {
      const lastTime = moment(item.time, "YYYY/M/D HH:mm:ss");
      item.box.prependTo(c);
      if (index !== this.jqArr.length - 1) { // 是否是最后一条消息
        if (!this.lastTime || Math.abs(lastTime.diff(this.lastTime, 's')) > 300) { // 没有最后的时间或时间差大于10分钟 就渲染时间标签
          $(`<p>${chatTimeFormat(lastTime, moment())}</p>`).prependTo(c);
        }
      } else { // 是最后一天消息需要显示时间
          $(`<p>${chatTimeFormat(lastTime, moment())}</p>`).prependTo(c);
      }
      this.lastTime = lastTime;
    })
    return this;
  }

  clearLastTime() {
    this.lastTime = null;
  }

}

export default new Message();
